<?php
/**
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file license.txt or that can be found at 
 * http://code.google.com/p/billboardce/wiki/License.
 *
 * @package    Slide_IndexController
 * @category   Controller
 * @license    http://code.google.com/p/billboardce/wiki/License New BSD License
 * @version    SVN: $Id: $
 */

/**
 * Main controller for the application
 *
 * @package    Slide_IndexController
 * @category   Controller
 */
class SlideController extends Zend_Controller_Action 
{   
          
    /**
     * Shows the slides that the user has created
     *
     */
    public function indexAction()
    {
        // @todo right now this lists all slides.  Should just list the ones the user has created
        
        $this->view->acl = array(
                               'details' => $this->_helper->hasAccess('details'),
                               'add'     => $this->_helper->hasAccess('add'),
                               'edit'    => $this->_helper->hasAccess('edit'),
                               'delete'  => $this->_helper->hasAccess('delete')
                           );
        
        $slide = new Slide();
        
        $this->view->slides = $slide->fetchAll(null, 'title');
        
        $this->_helper->pageTitle('slide-index-index:title');
    }
    
    /**
     * Returns the slide info to the slidestream editor
     */
    public function getSlideInfoAction()
    {
        
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->slideId)) {
            throw new Ot_Exception_Input('No slide ID provided');
        }
        
        $slide = new Slide();
        
        $thisSlide = $slide->find($get->slideId);
        
        if (is_null($thisSlide)) {
            throw new Ot_Exception_Input('Slide not found');
        }
        
        $this->_helper->viewRenderer->setNeverRender();
        $this->_helper->layout->disableLayout();
        
        echo Zend_Json::encode($thisSlide->toArray());
    }
    
    /**
     * Lets the user create a new or edit an existing slide.  If this is in an AJAX context, then 
     * we'll expect a slide stream ID to be given that the slide should also be
     * added to and we'll disable the layout.  If not slide ID is provided, then
     * the slide should be added
     */
    public function saveAction()
    {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNeverRender();
        
        if ($this->_request->isPost()) {
            
            if (!isset($_POST['data']) || empty($_POST['data'])) {
                echo Zend_Json::encode(array('rc' => 0, 'msg' => 'Error saving slide.  No data was found. Please try again'));
                return;
            }
            
            $postData = Zend_Json::decode($_POST['data']);
                     
                
            if (!isset($postData['slidestreamId']) && empty($postData['slidestreamId'])) {
                echo Zend_Json::encode(array('rc' => 0, 'msg' => 'Error adding slide.  No slidestream ID was given. Please try again'));
                return;
            }
            
            if (!isset($postData['slideType']) && empty($postData['slideType'])) {
                echo Zend_Json::encode(array('rc' => 0, 'msg' => 'Error adding slide.  No slide type was given. Please try again'));
                return;                
            }
            
            $slide = new Slide();
            $db = $slide->getAdapter();
            $db->beginTransaction();
            
            $isNewSlide = false;
            
            if (empty($postData['slideId'])) {
                
                $isNewSlide = true;
                
                $data = array(
                            'slideType' => $postData['slideType'],
                            'title'     => $postData['title']
                        );
                
                try {
                    $postData['slideId'] = $slide->insert($data);
                } catch (Exception $e) {
                    $db->rollBack();
                    echo Zend_Json::encode(array('rc' => 0, 'msg' => 'Error adding slide, please try again'));         
                }
            } else {
                
                $slideData = array(
                                'slideId' => $postData['slideId'],
                                'title'   => $postData['title']
                             );
    
                // the slide data is already in the database, so just update the slide's values
                try {
                    $slide->update($slideData, null);
                } catch (Exception $e) {
                    $db->rollBack();
                    throw new Ot_Exception_Data('Error saving slide in slide stream. ' . $e->getMessage());
                }
            }
            
            $slidePlugin = new Slide_Plugin();
            $slidePlugins = $slidePlugin->getEnabledPlugins();
            
            // save the type data 
            $typeObj = Slidetype::factory($postData['slideType']);

            try {
                $typeObj->saveConfigurationForm($postData['slideId'], $postData['typeData']);
            } catch (Exception $e) {
                $db->rollBack();
                throw new Ot_Exception_data('Error saving slidetype settings. ' . $e->getMessage());
            }
            
            // save slide option plugin data
            foreach ($slidePlugins as $p) {
                if (isset($postData['pluginData'][$p['name']]) && !empty($postData['pluginData'][$p['name']])) {                
                    
                    try {
                        $p['object']->saveConfigurationForm($postData['slideId'], $postData['pluginData'][$p['name']]);
                    }
                    catch (Exception $e) {
                        $db->rollBack();
                        throw new Ot_Exception_Data('Error saving slide plugin data. ' . $e->getMessage());
                    }
                }
            }
            
            if ($isNewSlide) {
                
                $slideStreamMap = new Slidestream_Slide();
                    
                $data = array(
                            'slidestreamId' => $postData['slidestreamId'],
                            'entityType'    => 'slide',
                            'entityTypeId'  => $postData['slideId'],
                            'order'         => 1
                        );
    
                try {
                    $slideStreamMap->insert($data);
                } catch (Exception $e) {
                    $db->rollBack();
                    echo Zend_Json::encode(array('rc' => 0, 'msg' => 'Error adding slide, please try again'));       
                }
            }
            
            $db->commit();
            
            $source = $typeObj->generateSlideThumbnail($postData['slideId']);
                            
            if (!is_null($source)) {
                
                $screenshotPath = realpath(APPLICATION_PATH . '/../public/screenshots');
        
                if (!is_dir($screenshotPath . '/' . $postData['slideId'])) {
                    mkdir($screenshotPath . '/' . $postData['slideId']);
                }
                
                $previewImage   = $screenshotPath . '/' . $postData['slideId'] . '/preview.jpg';
                $thumbnailImage = $screenshotPath . '/' . $postData['slideId'] . '/thumbnail.jpg';
                
                $sourcex = imagesx($source);
                $sourcey = imagesy($source);
                
                $sourcePallete = imagecreatetruecolor(300, 200);
                imagecopyresampled($sourcePallete, $source, 0, 0, 0, 0, 300, 200, $sourcex, $sourcey);
                imagejpeg($sourcePallete, $previewImage, 100);
                
                $thumbnailPallete = imagecreatetruecolor(120, 80);
                imagecopyresampled($thumbnailPallete, $source, 0, 0, 0, 0, 120, 80, $sourcex, $sourcey); 
                imagejpeg($thumbnailPallete, $thumbnailImage, 100);
                
                $updateImages = true;
                
                $thumbnailPath = 'screenshots/' . $postData['slideId'] . '/thumbnail.jpg';
                $previewPath   = 'screenshots/' . $postData['slideId'] . '/preview.jpg';
            }
            
            if ($isNewSlide) {

                echo Zend_Json::encode(array(
                                        'rc'            => 1,
                                        'msg'           => 'Slide added successfully',
                                        'slideId'       => $postData['slideId'],
                                        'slideType'     => $postData['slideType'],
                                        'updateImages'  => $updateImages,
                                        'thumbnailPath' => $thumbnailPath,
                                        'previewPath'   => $previewPath,
                                   ));
            } else {
                
                echo Zend_Json::encode(array(
                                        'rc'            => 2,
                                        'msg'           => 'Slide saved successfully',
                                        'slideId'       => $postData['slideId'],
                                        'slideType'     => $postData['slideType'],
                                        'updateImages'  => $updateImages,
                                        'thumbnailPath' => $thumbnailPath,
                                        'previewPath'   => $previewPath,
                                   ));
            }        
        }
    }
}